import pickle
import base64
from django_redis import get_redis_connection


def merge_cart_cookie_to_redis(request, response, user):
    """
    合并请求用户的购物车数据，将未登录保存在cookie里的保存到redis中
    遇到cookie与redis中出现相同的商品时以cookie数据为主，覆盖redis中的数据
    :param request: 用户的请求对象
    :param user: 当前登录的用户
    :param response: 响应对象，用于清楚购物车cookie
    :return:
    """
    # 获取cookie
    cookie_cart = request.COOKIES.get('cart_cookie')
    # 判断cookie是否为空
    if not cookie_cart:
        return response
    # 解密cookie数据
    cookie_cart = pickle.loads(base64.b64decode(cookie_cart.encode()))
    # 判断解密后的数据是否为空
    if cookie_cart is None:
        return response
    # 数据进行拆分  拆分hash  拆分集合
    cart = {}
    redis_cart_selected_add = []
    redis_cart_selected_remove = []
    for sku_id, count_selected_dict in cookie_cart.items():
        cart[sku_id] = count_selected_dict['count']
        if count_selected_dict['selected']:
            redis_cart_selected_add.append(sku_id)
        else:
            redis_cart_selected_remove.append(sku_id)
    # 建立redis链接对象
    redis_conn = get_redis_connection('cart')
    # 写入hash   写入集合
    redis_conn.hmset('cart_%s'%user.id, cart)
    if redis_cart_selected_add:
        redis_conn.sadd('cart_selected_%s' % user.id, *redis_cart_selected_add)
    if redis_cart_selected_remove:
        redis_conn.srem('cart_selected_%s' % user.id, *redis_cart_selected_remove)
    # 清除cookie
    response.delete_cookie('cart_cookie')
    # 返回结果
    return response